package com.yang.security.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zhy.base.tools.em.YesOrNo;
import com.yang.security.model.person.WeChatPerson;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by baipan
 * Date: 2019-12-18
 * Spring Security UserDetails具体对象类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Accessors(chain = true)
public class LoginUser implements UserDetails {


	private List<UserPermission> permissions;


	private String password;

	private String id;

	private String openId;

	private String userName;

	private String userRealName;

	private String phone;

	private Integer gander;

	/**
	 * 激活状态[0未激活 1激活]
	 */
	private Integer status;

	private String token;

	/**
	 * TokenService 中创建或者刷线Token的时候设置
	 * 登陆时间戳（毫秒）
	 */
	private Long loginTime;

	/**
	 * TokenService 中创建或者刷线Token的时候设置
	 * 过期时间戳
	 */
	private Long expireTime;


	public static LoginUser build(@NonNull WeChatPerson weChatPerson) {
		return LoginUser.builder()
				.password(weChatPerson.getPassword())
				.id(weChatPerson.getId())
				.openId(weChatPerson.getOpenId())
				.userName(weChatPerson.getUserName())
				.userRealName(weChatPerson.getUserRealName())
				.phone(weChatPerson.getPhone())
				.gander(weChatPerson.getGander())
				.status(weChatPerson.getEnable())
				.build();
	}


	/**
	 * 获取权限列表
	 */
	@Override
	@JsonIgnore
	public Collection<? extends GrantedAuthority> getAuthorities() {
		if (CollectionUtils.isEmpty(permissions)) {
			permissions = Lists.newArrayList();
		}


		return permissions.parallelStream()
				.filter(p -> StringUtils.isNotBlank(p.getPermissionKey()))
				.map(p -> new SimpleGrantedAuthority(p.getPermissionKey()))
				.collect(Collectors.toSet());
	}


	/**
	 * 获取用户名
	 */
	@Override
	public String getUsername() {
		return this.userName;
	}


	/**
	 * 账户是否未过期
	 */
	@JsonIgnore
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}


	/**
	 * 账户是否未锁定
	 */
	@JsonIgnore
	@Override
	public boolean isAccountNonLocked() {
		return YesOrNo.YES.getCode().equals(status);
	}


	/**
	 * 密码是否未过期
	 */
	@JsonIgnore
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}


	/**
	 * 账户是否激活
	 */
	@JsonIgnore
	@Override
	public boolean isEnabled() {
		return YesOrNo.YES.getCode().equals(status);
	}

}
